package com.elvish.oda.common.aspect;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.elvish.oda.busin.dao.LogDao;
import com.elvish.oda.busin.pojo.SysLog;
import com.elvish.oda.busin.pojo.User;
import com.elvish.oda.common.utils.CommonUtil;

/**
 * http请求切面类
 * 
 * @author Elvish
 *
 */
@Aspect
@Component
public class HttpAspect {

	private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

	@Autowired
	private LogDao logDao;

	@Pointcut("execution(public * com.elvish.oda.busin.controller.*.*(..))")
	public void log() {

	}

	@Before("log()")
	public void doBefore(JoinPoint joinPoint) {
		logger.info("before doing something...");
		ServletRequestAttributes butes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = butes.getRequest();
		User user = CommonUtil.getCurrentUser();
		// 排除未登录状态
		if (user != null) {
			SysLog log = new SysLog();
			log.setUsername(user.getName());
			log.setDate(new Date());
			log.setUrl(request.getRequestURI());
			log.setMethod(request.getMethod());
			log.setIp(request.getRemoteAddr());
			log.setClassMethod(
					joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
			log.setArgs(joinPoint.getArgs());
			logDao.save(log);
		}

		// url
		logger.info("url={}", request.getRequestURI());
		// method
		logger.info("method={}", request.getMethod());
		// ip
		logger.info("ip={}", request.getRemoteAddr());
		// class_method
		logger.info("class_method={}",
				joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
		// args
		logger.info("args={}", joinPoint.getArgs());
	}

	@After("log()")
	public void doAfter() {
		logger.info("after doing something...");
	}

	@AfterReturning(returning = "obj", pointcut = "log()")
	public void doAfterReturning(Object obj) {
		if (obj != null) {
			logger.info("doAfterReturning doing something... {}", obj.toString());
		}
	}

}
